<?php

namespace App\Http\Controllers\api\funds;

use App\Http\Controllers\api\base\BaseController;
use App\Http\Requests\funds\AccountRequest;
use App\Http\Requests\funds\CashRequest;
use App\Http\Resources\base\PageResource;
use App\Http\Resources\funds\MemberCollection;
use App\Http\Resources\funds\RebatePageCollection;
use App\Http\Resources\funds\RechargeCollection;
use App\Models\config\Config;
use App\Models\fund\Cash;
use App\Models\fund\Rebate;
use App\Models\user\MoneyDetail;
use App\Services\common\SmsService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class FundsController extends BaseController
{
   
    public function rechargeView()
    {
        $rows['money'] = $this->user->money;

        $rows['items'] = new RechargeCollection(RechargeConfig::orderBy('sort')->get());

        return success($rows);
    }

    /**
     * 会员购买界面
     */
    public function memberView()
    {

        $configs = MemberConfig::orderBy('sort')->remember(Carbon::now()->addSeconds(50))->get();

        return success(new MemberCollection($configs));

    }


    /**
     * 提现界面
     */
    public function cashView()
    {

        $rows['money'] = $this->user->money;
//        $rows['tips']  = Config::getConfig('cash_tips');

        $map['user_id'] = $this->user_id;

        $account = Cash::where($map)->select('account','name')->latest()->first();

        if (!$account){
            $account['account'] = '';
            $account['name']  = '';
        }

        $rows['account'] = $account;

        return success($rows);

    }

    /**
     * 用户提现账号编辑
     */
    public function editAccount(AccountRequest $request,SmsService $service)
    {
        $service->smsVerifier($request->phone,$request->code);

        $map['user_id'] = $this->user_id;
        $account = Account::firstOrNew($map);

        $account->name    = $request->name;
        $account->card    = $request->card;
        $account->account = $request->account;
        $account->phone   = $request->phone;
        $account->status  = 2;

        $result = $account->save();

        if ($result){
            return successWithMsg('提交成功,请耐心等待管理员审核!');
        }

    }


    /**
     * 提现申请
     */
    public function cash(CashRequest $request)
    {
        $this->ApiLimit(3,$this->user_id);

        if ($this->user->money < $request->money){
            //余额不足
            return error('余额不足!');
        }

        $map = $request->only(['money','type','name','account']);

        $map['user_id']    = $this->user_id;
        $map['status']     = 2;

        try{
            Cash::create($map);
            $this->user->decrement('money',$request->money);
            moneyDetailAdd($this->user_id,$request->money,'提现',0);
            \DB::commit();
        }catch (\Exception $e){
            return error($e->getMessage());
        }

        $this->DestroyLimit($this->user_id);

        return successWithMsg('提交成功,请耐心等待管理员审核!');
    }


    /**
     * 资金明细
     */
    public function details()
    {
        $map['user_id'] = $this->user_id;
        $rows = MoneyDetail::where($map)->latest()->paginate();

        return success( new PageResource($rows) );

    }


    /**
     * 钱包
     * @param FundService $service
     * @return Response
     */
    public function wallet(FundService $service)
    {
        $rows['total']    = (int) ($this->user->cash + $this->user->money);

        $map['user_id']   = $this->user_id;
        $map['type']      = 2;
        $rows['income']   = $service->detailTotal($map,date('Y'),date('m'));

        $map['type']      = 1;
        $rows['outlay']   = $service->detailTotal($map,date('Y'),date('m'));

        $map['type']      = 3;
        $rows['recharge'] = $service->detailTotal($map,date('Y'),date('m'));

        $map['type']      = 4;
        $rows['cash']     = $service->detailTotal($map,date('Y'),date('m'));

        return success($rows);

    }




    /**
     * 充值记录
     * @param Request $request
     * @return mixed
     */
    public function recharges(Request $request)
    {
        $Y = $request->Y??date('Y');
        $m = $request->m??date('m');

        $rows = Recharge::whereUserId($this->user_id)
            ->select(['pay_money','created_at','pay_type','title'])
            ->whereYear('created_at',$Y)
            ->whereMonth('created_at',$m)
            ->paginate();

        $sum = Recharge::whereUserId($this->user_id)
            ->whereYear('created_at',$Y)
            ->whereMonth('created_at',$m)
            ->sum('pay_money');

        $data = [
            'sum'          => $sum,
            'items'        => $rows->items(),
            'total'        => $rows->total(),
            'perPage'      => $rows->perPage(),
            'current_page' => $rows->currentPage(),

        ];

        return success($data);

    }


    /**
     * 提现记录
     * @param Request $request
     * @return mixed
     */
    public function cashes(Request $request,Cash $cash)
    {
        $Y = $request->Y??date('Y');
        $m = $request->m??date('m');

        $rows = $cash->whereUserId($this->user_id)
            ->select(['money','created_at','status','remark','name','account','type'])
            ->whereYear('created_at',$Y)
            ->whereMonth('created_at',$m)
            ->orderByDesc('id')
            ->paginate();

        return success(new PageResource( $rows));

    }

    /**
     * 支出明细
     */
    public function pays(Request $request,FundDetail $fundDetail)
    {
        $Y = $request->Y??date('Y');
        $m = $request->m??date('m');

        $type = $request->type??1;

        $rows = $fundDetail->whereUserId($this->user_id)
            ->select(['amount','created_at','status','type','title','remark','relation_user'])
            ->whereYear('created_at',$Y)
            ->whereMonth('created_at',$m)
            ->whereType($type)
            ->orderByDesc('id')
            ->paginate();
        array_map(function ($item){
            $item->append(['relation_name']);
            $item->addHidden(['relation_user']);
        },$rows->items());

        $sum = $fundDetail->whereUserId($this->user_id)
            ->whereType($type)
            ->whereYear('created_at',$Y)
            ->whereMonth('created_at',$m)
            ->sum('amount');

        $data = [
            'sum'          => $sum,
            'items'        => $rows->items(),
            'total'        => $rows->total(),
            'perPage'      => $rows->perPage(),
            'current_page' => $rows->currentPage(),

        ];
        return success($data);
    }


    public function rebates(Request $request)
    {
        if (!is_numeric($request->lv)){
            $map['lv'] = 1;
        }else{
            $map['lv'] = $request->lv;
        }
        $map['user_id'] = $this->user_id;
        $map['type'] = 1;

        $rows = Rebate::where($map)->with('RelationUser','order','order_detail')->orderByDesc('id')->paginate();

        return success( new RebatePageCollection( $rows ) );
    }
    
    
    
    
    
    
}
